#include "contouritem.h"

#include <QGraphicsSceneMouseEvent>
#include <iostream>
#include <QPaintEngine>
#include "geometrydata.h"
#include "config.h"
#include <QRgb>
#include <QGraphicsScene>
#include <QGraphicsView>
#include "datastructures.h"


ContourItem::ContourItem(Contour *ctr)
{
    this->contour = ctr;
    select_ = false;
    //updateParams();
}

void ContourItem::updateParams()
{
    QVector <QPointF> pv;
    for (int i =0; i< contour->points.size(); i++)
    {
        double x = contour->points[i]->x;
        double y = contour->points[i]->y;
        pv.push_back(QPointF(x,y));
    }

    polygon = QPolygonF(pv);
    pen = QPen(Config::meshColor());
    brush_empty = QBrush(Qt::NoBrush);
    double color_h = 0;
    double color_length = 0;
   // color_length = abs(GeometryData::max_param - GeometryData::min_param);
   // color_h = (360.0/color_length)*(contour.param);//+abs(GeometryData::min_param));
    brush_colored = QBrush(QColor::fromHsvF(color_h/360.0,1,1));

    pen.setWidth(0);
}

QRectF ContourItem::boundingRect() const
{
    return polygon.boundingRect();
}

QPainterPath ContourItem::shape() const
{
    QPainterPath path;
    path.addPolygon(polygon);
    return path;
}

void ContourItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    updateParams();
    if (!select_)
        painter->setBrush(brush_empty);
    else
        painter->setBrush(brush_colored);

    if (Config::drawColoredMesh())
        painter->setBrush(brush_colored);

    if (!Config::drawMesh())
        pen = QPen(Qt::NoPen);
    else
        pen = QPen(Config::meshColor(),0);

    painter->setPen(pen);
    painter->drawPolygon(polygon);

    if (Config::drawInfoText())
    {
        for (int i =0; i < contour->points.size(); i++)
         {
            QPointF p( contour->points[i]->x,contour->points[i]->y);
            p = this->scene()->views()[0]->mapFromScene(p);
            painter->resetTransform();
            painter->setPen(QPen(Qt::black));
            painter->setFont(QFont("Arial",10));

            painter->drawText(p,QString::number(i));
        }
    }
}

void ContourItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsItem::mousePressEvent(event);
    update();
}

void ContourItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsItem::mouseMoveEvent(event);
}

void ContourItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsItem::mouseReleaseEvent(event);
}
